<?php
/**
 * Created by PhpStorm.
 * Script Name: BotGroup.php
 * Create: 2023/2/10 17:11
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\service;


use plugin\wechat\app\model\BotMember as MemberM;
use plugin\wechat\app\model\BotGroupmember as GroupMemberM;
use plugin\wechat\app\service\Bot as BotService;
use plugin\wechat\app\service\BotFriend as FriendService;
use plugin\wechat\extend\WxBot\Driver\Cat;
use plugin\wechat\extend\WxBot\Driver\My;

class BotGroup extends Common
{
    /**
     * 获取群组列表[wxid => nickname]
     * @param null $uin
     * @param array $where
     * @return array
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function getWxidToNickname($uin = null, $where = []){
        if(is_null($uin)){
            $uin = \request()->botInfo['uin'];
        }
        $query = MemberM::where('uin', $uin)
            ->where('type', BotService::GROUP);
        $where && $query = $query->where($where);
        return $query->column('nickname','wxid');
    }

    /**
     * 拉取最新群组列表
     * @param $bot
     * @return int
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function pullGroups($bot){
        /**
         * @var $client Cat|My
         */
        $client = BotService::getRobotClient($bot);
        $res = $client->getGroups([
            'data' => ['robot_wxid' => $bot['uin'], 'is_refresh' => 1, 'uuid' => $bot['uuid']]
        ]);
        $wxid_arr = [];
        $list = [];

        switch ($bot['protocol']) {
            case Bot::PROTOCOL_XBOT:
                if($res['code'] && count($res['data'])){
                    $list = $res['data'];
                    $wxid_arr = [];
                    foreach ($list as $k => $v){
                        $nickname = filter_emoji($v['nickname']);
                        $wxid = $v['wxid'];
                        $headimgurl = $v['avatar'];
                        $wxid_arr[] = $wxid;
                        if($data = FriendService::getMember($wxid, $bot['uin'])){
                            MemberM::update([
                                'id' => $data['id'],
                                'nickname' => $nickname,
                                'headimgurl' => $headimgurl
                            ]);
                        }else{
                            MemberM::create([
                                'company_id' => $bot['company_id'],
                                'uin' => $bot['uin'],
                                'nickname' => $nickname,
                                'wxid' => $wxid,
                                'type' => Bot::GROUP,
                                'headimgurl' => $headimgurl
                            ]);
                        }
                    }
                }
                break;
            case Bot::PROTOCOL_CAT:
                if($res['code'] && count($res['data'])){
                    $list = $res['data'];
                    $wxid_arr = [];
                    foreach ($list as $k => $v){
                        $nickname = filter_emoji($v['nickname']);
                        $wxid = $v['wxid'];
                        $wxid_arr[] = $wxid;
                        if($data = FriendService::getMember($wxid, $bot['uin'])){
                            MemberM::update([
                                'id' => $data['id'],
                                'nickname' => $nickname,
                            ]);
                        }else{
                            MemberM::create([
                                'company_id' => $bot['company_id'],
                                'uin' => $bot['uin'],
                                'nickname' => $nickname,
                                'wxid' => $wxid,
                                'type' => Bot::GROUP
                            ]);
                        }
                    }
                }
                break;
            case Bot::PROTOCOL_MY:
                if($res['code'] && count($res['ReturnJson'])){
                    $list = $res['ReturnJson'];
                    $wxid_arr = [];
                    foreach ($list as $k => $v){
                        $nickname = filter_emoji($v['nickname']);
                        $headimgurl = $v['avatar'];
                        $wxid = $v['wxid'];
                        $wxid_arr[] = $wxid;
                        if($data = FriendService::getMember($wxid, $bot['uin'])){
                            MemberM::update([
                                'id' => $data['id'],
                                'nickname' => $nickname,
                                'headimgurl' => $headimgurl
                            ]);
                        }else{
                            MemberM::create([
                                'company_id' => $bot['company_id'],
                                'uin' => $bot['uin'],
                                'nickname' => $nickname,
                                'wxid' => $wxid,
                                'type' => Bot::GROUP,
                                'headimgurl' => $headimgurl
                            ]);
                        }
                    }
                }
                break;
            default:
                if($res['code'] && count($res['data'])){
                    $list = $res['data'];
                    $wxid_arr = [];
                    foreach ($list as $k => $v){
                        $nickname = filter_emoji($v['nickname']);
                        $wxid = $v['wxid'];
                        $wxid_arr[] = $wxid;
                        if($data = FriendService::getMember($wxid, $bot['uin'])){
                            MemberM::update([
                                'id' => $data['id'],
                                'nickname' => $nickname,
                            ]);
                        }else{
                            MemberM::create([
                                'company_id' => $bot['company_id'],
                                'uin' => $bot['uin'],
                                'nickname' => $nickname,
                                'wxid' => $wxid,
                                'type' => Bot::GROUP
                            ]);
                        }
                    }
                }
                break;
        }
        //删除无效
        MemberM::where('uin', $bot['uin'])
            ->where('type', BotService::GROUP)
            ->where('wxid' , 'notin', $wxid_arr)
            ->delete();
        return count($list);
    }

    /**
     * 拉取最新群成员
     * @param $bot
     * @param $group
     * @return int
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function pullGroupMembers($bot, $group){
        /**
         * @var $bot_client Cat|My
         */
        $bot_client = BotService::getRobotClient($bot);
        $res = $bot_client->getGroupMembers([
            'robot_wxid' => $bot['uin'],
            'uuid' => $bot['uuid'],
            'group_wxid' => $group['wxid'],
        ]);
        $wxid_arr = [];
        $list = [];
        switch ($bot['protocol']) {
            case Bot::PROTOCOL_CAT:
                if($res['code'] && count($res['data'])) {
                    $list = $res['data'];
                    $wxid_arr = [];
                    foreach ($list as $k => $v){
                        $nickname = filter_emoji($v['nickname']);
                        $group_nickname = $nickname;
                        $username = $v['wx_num'];
                        $wxid = $v['wxid'];
                        $wxid_arr[] = $wxid;
                        if($data = self::getGroupMember(['group_id' => $group['id'], 'wxid' => $wxid])){
                            GroupMemberM::update([
                                'id' => $data['id'],
                                'nickname' => $nickname,
                                'group_nickname' => $group_nickname,
                                'username' => $username
                            ]);
                        }else{
                            GroupMemberM::create([
                                'company_id' => $bot['company_id'],
                                'bot_id' => $bot['id'],
                                'group_id' => $group['id'],
                                'nickname' => $nickname,
                                'group_nickname' => $group_nickname,
                                'username' => $username,
                                'wxid' => $wxid
                            ]);
                        }
                    }

                } else{
                    dao_log()->error("pullGroupMembers:" . json_encode($res, JSON_UNESCAPED_UNICODE));
                }
                break;
            case Bot::PROTOCOL_MY:
            case Bot::PROTOCOL_VLW:
                if($res['code'] && count($res['ReturnJson'])) {
                    $list = $res['ReturnJson']['member_list'];
                    $wxid_arr = [];
                    foreach ($list as $k => $v){
                        $nickname = filter_emoji($v['nickname']);
                        $group_nickname = filter_emoji($v['group_nickname']);
                        $headimgurl = $v['avatar'];
                        $username = $v['wx_num'];
                        $wxid = $v['wxid'];
                        $wxid_arr[] = $wxid;
                        if($data = self::getGroupMember($wxid, $group['id'])){
                            GroupMemberM::update([
                                'id' => $data['id'],
                                'nickname' => $nickname,
                                'group_nickname' => $group_nickname,
                                'username' => $username,
                                'headimgurl' => $headimgurl
                            ]);
                        }else{
                            GroupMemberM::create([
                                'company_id' => $bot['company_id'],
                                'bot_id' => $bot['id'],
                                'group_id' => $group['id'],
                                'nickname' => $nickname,
                                'group_nickname' => $group_nickname,
                                'username' => $username,
                                'wxid' => $wxid,
                                'headimgurl' => $headimgurl
                            ]);
                        }
                    }
                } else{
                    dao_log()->error("pullGroupMembers:" . json_encode($res, JSON_UNESCAPED_UNICODE));
                }
                break;
            default:
                if($res['code'] && count($res['data'])) {
                    $list = $res['data'];
                    $wxid_arr = [];
                    foreach ($list as $k => $v){
                        $nickname = empty($v['nickname']) ? '' : filter_emoji($v['nickname']);
                        $group_nickname = empty($v['group_nickname']) ? $nickname : filter_emoji($v['group_nickname']);
                        $username = empty($v['username']) ? '' : $v['username'];
                        $wxid = $v['wxid'];
                        $wxid_arr[] = $wxid;
                        if($data = self::getGroupMember($wxid, $group['id'])){
                            $update = [
                                'id' => $data['id'],
                                'nickname' => $nickname,
                                'group_nickname' => $group_nickname,
                                'username' => $username
                            ];
                            $nickname && $update['nickname'] = $nickname;
                            $group_nickname && $update['group_nickname'] = $group_nickname;
                            $username && $update['username'] = $username;
                            GroupMemberM::update($update);
                        }else{
                            GroupMemberM::create([
                                'bot_id' => $bot['id'],
                                'group_id' => $group['id'],
                                'nickname' => $nickname,
                                'group_nickname' => $group_nickname,
                                'username' => $username,
                                'wxid' => $wxid
                            ]);
                        }
                    }
                } else{
                    dao_log()->error("pullGroupMembers:" . json_encode($res, JSON_UNESCAPED_UNICODE));
                }
                break;
        }

        //删除无效数据
        if(count($wxid_arr)){
            GroupMemberM::where([
                ['company_id', '=', $bot['company_id']],
                ['group_id' ,'=', $group['id']],
                ['wxid', 'notin', $wxid_arr]
            ])->delete();
        }
        return count($list);
    }

    /**
     * 获取数据库群成员信息
     * @param string $wxid
     * @param int $group_id
     * @return array|mixed|\think\db\Query|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function getGroupMember($wxid = '', $group_id = 0)
    {
        return GroupMemberM::where('wxid', $wxid)
            ->where('group_id', $group_id)
            ->find();
    }
}